package controllers

import (
	"fmt"
	"github.com/goravel/framework/contracts/database/orm"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"github.com/spf13/cast"
	"goravel/app/models"
	"goravel/packages/utils"
	"strconv"
)

type RefillcardController struct {
	//Dependent services
	SearchByParamsService
	utils.Utils
}

func NewRefillcardController() *RefillcardController {
	return &RefillcardController{
		//Inject services
	}
}

func (r *RefillcardController) Index(ctx http.Context) http.Response {
	pageSize := ctx.Request().Query("pageSize", "1")
	pageSizeInt, _ := strconv.Atoi(pageSize)
	order := ctx.Request().Query("order")
	sort := ctx.Request().Query("sort")
	refillcardLogs := []models.Refillcard{}

	var total int64
	currentPage := ctx.Request().Query("currentPage", "1")
	currentPageInt, _ := strconv.Atoi(currentPage)
	queries := ctx.Request().Queries()
	if order != "" || sort != "" {
		facades.Orm().Query().Scopes(r.SearchByParams(ctx.Request().Queries())).
			Order(sort+" "+order).Paginate(currentPageInt, pageSizeInt, &refillcardLogs, &total)
	} else {
		facades.Orm().Query().Scopes(r.SearchByParams(queries)).Order("id desc").
			Paginate(currentPageInt, pageSizeInt, &refillcardLogs, &total)
	}

	return ctx.Response().Success().Json(http.Json{
		"data":  refillcardLogs,
		"total": total,
		"links": map[string]interface{}{
			"first": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=1",
			//最后一页应该是总数除以每页的数量取整
			"last": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=" + strconv.Itoa(int(total)/pageSizeInt),
			"prev": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=" + strconv.Itoa(currentPageInt-1),
			"next": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=" + strconv.Itoa(currentPageInt+1),
		},
		"meta": map[string]interface{}{
			"total_page":   int(total) / pageSizeInt,
			"current_page": currentPageInt,
			"per_page":     pageSizeInt,
			"total":        total,
		},
	})
}

func (r *RefillcardController) BatchCreate(ctx http.Context) http.Response {
	unit := ctx.Request().Input("unit", "day")
	number := ctx.Request().Input("number", "1")
	var user models.User
	facades.Auth().User(ctx, &user)
	if user.ID != 1 && user.ID != 2 {
		return ctx.Response().Status(http.StatusBadRequest).Json(http.Json{
			"message": "无权操作",
		})
	}
	numberInt, _ := strconv.Atoi(number)
	for i := 0; i < numberInt; i++ {
		facades.Orm().Query().Create(&models.Refillcard{
			//UserID: user.ID,
			Secret: r.GenerateCardSecret(),
			Unit:   unit,
			State:  0,
		})
	}
	return ctx.Response().Success().Json(http.Json{
		"message": "生成成功",
	})
}

// 为用户充值Charge
func (r *RefillcardController) Charge(ctx http.Context) http.Response {

	user_id := ctx.Request().Input("id")
	refillcard_id := ctx.Request().Input("refillcard_id")
	var refillcard models.Refillcard
	facades.Orm().Query().Where("secret=?", refillcard_id).First(&refillcard)
	if refillcard.ID == 0 {
		return ctx.Response().Status(http.StatusBadRequest).Json(http.Json{
			"message": "充值卡不存在",
		})
	}
	if refillcard.State == 1 {
		return ctx.Response().Status(http.StatusBadRequest).Json(http.Json{
			"message": "充值卡已使用",
		})
	}
	var user models.User
	facades.Orm().Query().Where("id=?", cast.ToInt(user_id)).First(&user)
	if user.ID == 0 {
		return ctx.Response().Status(http.StatusBadRequest).Json(http.Json{
			"message": "用户不存在",
		})
	}
	switch refillcard.Unit {
	case "day":
		user.ExpireTime = carbon.NewDateTime(carbon.Parse(user.ExpireTime.String()).AddDay())
	case "week":
		user.ExpireTime = carbon.NewDateTime(carbon.Parse(user.ExpireTime.String()).AddWeek())
	case "month":
		user.ExpireTime = carbon.NewDateTime(carbon.Parse(user.ExpireTime.String()).AddMonth())
	case "half_year":
		user.ExpireTime = carbon.NewDateTime(carbon.Parse(user.ExpireTime.String()).AddQuarters(2))
	case "year":
		user.ExpireTime = carbon.NewDateTime(carbon.Parse(user.ExpireTime.String()).AddYear())
	}
	//开启事务
	err := facades.Orm().Transaction(func(tx orm.Transaction) error {
		refillcard.State = 1
		refillcard.UserName = user.Mobile
		if _, err2 := tx.Update(&user); err2 != nil {
			return err2
		}
		if _, err1 := tx.Update(&refillcard); err1 != nil {
			return err1
		}
		var order models.Order
		//202312121841223的形式
		order.OrderNo = "CZ" + carbon.Now().Format("YmdHis")
		order.UserID = user.ID
		order.RefillcardID = refillcard.ID
		order.RefillcardTxt = fmt.Sprintf("账户：%s,消费充值卡，卡类：%s,卡号：%d，卡密：%s", user.Mobile, refillcard.Unit, refillcard.ID, refillcard.Secret)
		if err3 := tx.Create(&order); err3 != nil {
			return err3
		}
		//关联保存
		return tx.Model(&user).Association("Refillcards").Append([]*models.Refillcard{&refillcard})
	})
	if err != nil {
		return ctx.Response().Status(http.StatusBadRequest).Json(http.Json{
			"message": "充值失败，请联系管理员！",
		})
	}

	return ctx.Response().Success().Json(http.Json{
		"message": "充值成功",
	})

}
